import API from './../../api/oss'
// import html2canvas from 'html2canvas'
import axios from 'axios'
export default {
  data() {
    return {}
  },
  methods: {
    async fetchDownLoad(data = {}, url = '/oss/list') {
      const result = await API.list(data, url)
      console.log(result, '哈哈哈下载啦')
      if (!result) {
        this.$message.error('暂无可下载的模版')
        return
      }
      const imgtype = [
        'bmp',
        'jpg',
        'png',
        'tif',
        'gif',
        'pcx',
        'tga',
        'exif',
        'fpx',
        'svg',
        'psd',
        'cdr',
        'pcd',
        'dxf',
        'ufo',
        'eps',
        'ai',
        'raw',
        'WMF',
        'prj,dwg,dxf,rul  '
      ]
      if (result && result.list && result.list.length) {
        result.list.forEach((element, i) => {
          if (imgtype.includes(element.ossSuffix)) {
            setTimeout(() => {
              this.fetchImg(element.ossUrl, element.ossName)
            }, i * 500)
          } else {
            // window.open(element.ossUrl)
            const a = document.createElement('a')
            a.setAttribute('href', element.ossUrl)
            a.setAttribute('download', '')
            a.click()
          }
        })
      }
    },

    async fetchImg(img, name = '下载', errorInfo = '导出失败') {
      if (
        img.endsWith('ai') ||
        img.endsWith('prj') ||
        img.endsWith('dwg') ||
        img.endsWith('dxf') ||
        img.endsWith('rul') ||
        img.endsWith('xlsx') ||
        img.endsWith('excel')
      ) {
        // window.open(img)
        const a = document.createElement('a')
        a.setAttribute('href', img)
        a.setAttribute('download', '')
        a.click()
        return
      }
      try {
        const response = await axios({
          methods: 'get',
          headers: {
            'Content-Type': 'multipart/form-data',
            token: localStorage.userId,
            accountId: localStorage.accountId
          },
          url: img.replace('https:', window.location.protocol),
          responseType: 'blob'
        })
        const blob = await new Blob([response.data], { type: 'image/png' })
        // 创建隐藏的可下载链接
        const objectUrl = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        // 地址
        a.href = objectUrl
        // 修改文件名
        a.download = name
        // 触发点击
        document.body.appendChild(a)
        a.click()
        // 移除
        window.URL.revokeObjectURL(blob)
        setTimeout(() => document.body.removeChild(a), 1000)
      } catch (error) {
        this.$message.error(errorInfo)
      }
    }
  }
}
